﻿package controller

import (
	"app2word/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/unidoc/unioffice/document"
	"github.com/unidoc/unioffice/schema/soo/wml"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

type FileNode struct {
	Title    string       `json:"title"`
	Key      string       `json:"key"`
	Size     float64      `json:"size"`
	Children *[]*FileNode `json:"children"`
}

func Files(ctx *gin.Context) {
	j := make(map[string]interface{})
	ctx.BindJSON(&j)
	abs := j["abs"].(string)
	fns := make([]*FileNode, 0)
	fn := FileNode{abs, abs, 0.0, &fns}
	err := __walk__(abs, &fn, fn.Key)
	if err != nil {
		build, _ := utils.Build(-1, err.Error(), nil)
		ctx.JSON(http.StatusBadRequest, build)
		return
	}
	build, _ := utils.Build(1, "success", &fn)
	ctx.JSON(http.StatusOK, build)

}

func Export2Word(ctx *gin.Context) {
	j := make(map[string][]string)
	ctx.BindJSON(&j)
	checkeds := j["checked"]
	__generateDocx__(checkeds, ctx.Writer)
	//ctx.File(fn
	ctx.Writer.Flush()
	//build, _ := utils.Build(1, "export success", nil)
	//ctx.JSON(http.StatusOK, build)
}

func __generateDocx__(checkeds []string, writer io.Writer) {
	doc := document.New()
	defer doc.Close()
	for _, name := range checkeds {
		file, err := os.Open(name)
		if err != nil {
			fmt.Println("解析失败：", name)
			continue
		}
		defer file.Close()
		run, err := createParaRun(doc, file.Name())
		run.Properties().SetBold(true)
		run.Properties().SetHighlight(wml.ST_HighlightColorYellow)
		content, err := ioutil.ReadAll(file)
		if err != nil {
			fmt.Println("解析失败：", name)
			continue
		}
		createParaRun(doc, string(content))
	}
	doc.Save(writer)
	//t := strconv.Itoa(int(time.Now().UnixNano()))
	//name := "app-" + t + ".docx"
	//doc.SaveToFile(name)
	//return name
}

func createParaRun(doc *document.Document, content string) (*document.Run, error) {
	//将windows下 \r\n 替换成linux下
	content = strings.Replace(content, "\r\n", "\n", -1)
	//将linux 下\n 替换成windows下\r\n
	content = strings.Replace(content, "\n", "\r\n", -1)
	para := doc.AddParagraph()
	run := para.AddRun()
	run.AddText(string(content))
	return &run, nil
}

func __walk__(abs string, fn *FileNode, key string) error {
	f, err := os.Stat(abs)
	if err != nil {
		return err
	}
	if f.IsDir() {
		fs, _ := ioutil.ReadDir(abs)
		i := 0
		for _, f := range fs {
			fns := make([]*FileNode, 0)
			abs = abs + "/" + f.Name()
			//key = key + "-" + strconv.Itoa(i)
			fileNode := FileNode{abs, abs, 0.0, &fns}
			*fn.Children = append(*fn.Children, &fileNode)
			__walk__(abs, &fileNode, key)
			abs = abs[:len(abs)-len(f.Name())-1]
			//key = key[:len(key)-len(strconv.Itoa(i))-1]
			i = i + 1
		}
		return nil
	}
	fn.Size = float64(f.Size()) / (1024.0 * 1024.0)
	return nil
}
